<?php

namespace Admin\Controller;

use Think\Controller;
use Think\Auth;

class CommonController extends Controller
{
    var $product;
    var $category;
    var $gallery;
    var $advert;
    var $customer;
    var $order;
    var $address;

    public function __construct()
    {
        parent::__construct();
        $this->product = M("Product");
        $this->category = M("Category");
        $this->gallery = M("Gallery");
        $this->advert = M("Advert");
        $this->customer = M("Customer");
        $this->order = M("Orders");
        $this->address = M("Address");

        $this->count();
        $this->check_login();
        $this->all_menus();
    }

    /**
     * 统计数据
     */
    public function count()
    {
        //统计商品总数
        $this->product_counts = $this->product->where("status = 1")->count();
        //统计广告总数
        $this->advert_counts = $this->advert->count();
        //统计商品回收站总数
        $this->product_recycles = $this->product->where("status = 0")->count();
        //统计订单数
        $this->order_counts = $this->order->count();
        //统计会员数
        $this->customer_counts = $this->customer->count();

        //统计用户数
        $this->user_counts = M('User')->count();
    }

    /**
     * 检查用户有没有登录
     */
    function check_login()
    {
        //如果cookie不存在，跳回登录页面
        if (!isset($_COOKIE['token'])) {
            $this->error('你未登录，请登录后访问', U('User/login'));
        }
        //如果token与数据库里面不匹配，表示用户伪造了token
        $User = M('User');
        $token = $_COOKIE['token'];
        $user = $User->where("token = '$token'")->find();
        if (!$user) {
            $this->error('非法登录，请重新登录', U('User/login'));
        }

//        //当前面的各个模块的增删改查完成后，开启下面的代码即可实现权限管理
//        $Auth = new Auth();
//        $name = MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME;
//        if (!$Auth->check($name, $user['id'])) {
//            $this->error('您没有权限访问当前页面,请与管理员联系', U('User/no_auth'));
//        }

        $_SESSION['user'] = $user;
        $this->assign('user', $_SESSION['user']);
    }

    /***
     * 公共数据
     */
    private function all_menus()
    {
        //查出所有菜单权限
        $AuthRule = D('AuthRule');

        //一级菜单
        $menus = $AuthRule->where('parent_id = 0')->select();
        //二级菜单
        foreach ($menus as $key => $value) {
            $menus[$key]['children'] = $AuthRule->where("parent_id = $value[id]")->select();
            //三级菜单
            foreach ($menus[$key]['children'] as $k => $v) {
                $menus[$key]['children'][$k]['child'] = $AuthRule->where("parent_id = $v[id]")->select();
            }
        }
        $this->assign('menus', $menus);
    }

}